import {
  login,
  logout,
  getInfo,
  getTimeStamp,
  changePassword,
  resetRamKey,
  getRamKey
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  fnAddDynamicMenuRoutes
} from '@/utils/auth'
import { menuDataTranslate, findIndex } from '@/utils'
import { encryptPassword } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    id: 0,
    name: '',
    userType: 1,
    selections: [],
    rangeSelections: [],
    keys: {
      storage: {
        username: 'USER_NAME',
        lang: 'LANG'
      }
    },
    token: getToken(),
    username: '',
    logoUrl: '',
    avatar: '',
    menuList: [],
    orgId: '',
    userInfo: {},
    isAddDynamicMenuRoutes: false,
    btnPermissions: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    localStorage.removeItem(state.keys.storage.username)
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_LOGO_URL: (state, name) => {
    state.logoUrl = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENU_LIST: (state, menuList) => {
    state.menuList = menuList
    state.isAddDynamicMenuRoutes = true
  },
  SET_ORG_ID: (state, orgId) => {
    state.orgId = orgId
  },
  SET_USER_INFO: (state, info) => {
    state.userInfo = info
    localStorage.setItem(state.keys.storage.username, JSON.stringify(info))
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.btnPermissions = permissions.map(
      (permission) => permission.menuFuncCode
    )
  }
}

const actions = {
  // user login
  // async login(store, userInfo) {
  //   const { username, password, captcha } = userInfo
  //   const { timestamp } = await getTimeStamp()
  //   const json = JSON.stringify({
  //     key: timestamp,
  //     password
  //   })
  //   const encryptedPassword = encryptPassword(json)

  //   const _userInfo = await login({
  //     username: username.trim(),
  //     password,
  //     code: captcha
  //   })

  //   const { characterStatus, token } = _userInfo

  //   if (characterStatus !== 1) {
  //     if (characterStatus === 2) {
  //       store.dispatch('resetToken').then(() => {
  //         window.location.href = `http://localhost:8080/#/account-status?token=${response.token}`
  //       })
  //     } else if (characterStatus === 3) {
  //       store.dispatch('resetToken').then(() => {
  //         window.location.href = `http://localhost:8080/#/resubmit-form?token=${response.token}`
  //       })
  //     }
  //   } else {
  //     store.dispatch('setUserInfo', _userInfo)
  //     setToken(token)
  //     localStorage.setItem(
  //       store.state.keys.storage.username,
  //       JSON.stringify(_userInfo)
  //     )
  //     return Promise.resolve()
  //   }
  // },

  updateId(state, id) {
    state.id = id
  },
  updateName(state, name) {
    state.name = name
  },
  updateType(state, type) {
    state.userType = type
  },
  updateAccount(state, account) {
    state.account = account
  },
  UPDATE_SELECTIONS({ selections }, selection) {
    const index = findIndex(selections, selection)
    if (index === -1) {
      selections.push(selection)
    }
  },
  REMOVE_SELECTIONS({ selections }, selection) {
    // console.log(selections[0], selection)

    const index = findIndex(selections, selection)
    if (index > -1) {
      selections.splice(index, 1)
    }
  },
  CLEAR_SELECTIONS(state) {
    state.selections.splice(0, state.selections.length)
  },
  //
  UPDATE_RANGE_SELECTIONS({ rangeSelections }, selection) {
    const index = findIndex(rangeSelections, selection)
    if (index === -1) {
      rangeSelections.push(selection)
    }
  },
  REMOVE_RANGE_SELECTIONS({ rangeSelections }, selection) {
    // console.log(rangeSelections[0], selection)
    const index = findIndex(rangeSelections, selection)
    if (index > -1) {
      rangeSelections.splice(index, 1)
    }
  },
  CLEAR_RANGE_SELECTIONS(state) {
    state.rangeSelections.splice(0, state.rangeSelections.length)
  },
  // 从docConfig-company进入判断,表格多选时使用
  // UPDATE_RANGE_SELECTIONS_COMPANY ({rangeSelections}, selection) {
  //   let index = JSON.stringify(rangeSelections).indexOf(`"userId":${selection.userId}`)
  //   if (index === -1) {
  //     rangeSelections.push(selection)
  //   }
  // },
  // REMOVE_RANGE_SELECTIONS_COMPANY ({rangeSelections}, selection) {
  //   rangeSelections.forEach((item, index) => {
  //     if (item.userId === selection.userId) {
  //       rangeSelections.splice(index, 1)
  //     }
  //   })
  // },
  UPDATE_RANGE_SELECTIONS_COMPANY_RADIO({ rangeSelections }, selection) {
    rangeSelections.splice(0, rangeSelections.length)
    rangeSelections.push(selection)
  },
  login(store, userInfo) {
    const { username, password, captcha } = userInfo
    return new Promise((resolve, reject) => {
      getTimeStamp()
        .then((res) => {
          const { timestamp } = res
          // const json = JSON.stringify({
          //   timestamp,
          //   password
          // })
          const encryptedPassword = encryptPassword({ timestamp, password })
          login({
            username: username.trim(),
            password: encryptedPassword,
            code: captcha
          })
            .then((response) => {
              const { characterStatus } = response
              if (characterStatus && characterStatus !== 1) {
                if (characterStatus === 2) {
                  store.dispatch('resetToken').then(() => {
                    window.location.href = `http://localhost:8080/#/account-status?token=${response.token}`
                  })
                } else if (characterStatus === 3) {
                  store.dispatch('resetToken').then(() => {
                    window.location.href = `http://localhost:8080/#/resubmit-form?token=${response.token}`
                  })
                }
              } else {
                store.dispatch('setUserInfo', response)
                setToken(response.token)
                localStorage.setItem(
                  store.state.keys.storage.username,
                  JSON.stringify(response)
                )
                resolve()
              }
            })
            .catch((error) => {
              reject(error)
            })
        })
        .catch((err) => {
          console.log(err)
        })
    })
  },
  async resetRamKey({commit},form) {
    const { timestamp } = await getTimeStamp()
    const password  = form.operPassword
    const encryptedPassword = encryptPassword({ timestamp, password })
    return await resetRamKey(form.userId,{
      operPassword: encryptedPassword,
      code: form.code,
      ramUserId: form.userId
    })
  },
  async getRamKey({commit},form) {
    const { timestamp } = await getTimeStamp()
    const password = form.operPassword
    const encryptedPassword = encryptPassword({ timestamp, password })
    return await getRamKey(form.userId,{
      operPassword: encryptedPassword,
      code: form.code,
      ramUserId: form.userId
    })
  },
  async changePassword({ commit }, form) {
    const { timestamp } = await getTimeStamp()
    // let json = JSON.stringify({
    //   timestamp,
    //   password: form.newPassword
    // })

    const encryptedNewPassword = encryptPassword({ timestamp, password: form.newPassword })

    // json = JSON.stringify({
    //   timestamp,
    //   password: form.oldPassword
    // })
    const encryptedOldPassword = encryptPassword({ timestamp, password: form.oldPassword })
    return await changePassword({
      oldPassword: encryptedOldPassword,
      newPassword: encryptedNewPassword,
      code: form.code
    })
  },

  setUserInfo({ commit }, userInfo) {
    commit('SET_TOKEN', userInfo.token)
    commit('SET_NAME', userInfo.name)
    commit('SET_USERNAME', userInfo.username)
    commit('SET_ORG_ID', userInfo.orgId)
    commit('SET_LOGO_URL', userInfo.logoUrl)
    commit('SET_USER_INFO', userInfo)
    commit('SET_PERMISSIONS', userInfo.menuFunctionList)
  },

  getInfo({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((data) => {
          dispatch('setUserInfo', data)
          const menuList = menuDataTranslate(
            data.platformInfoList[0].menuList,
            'menuId',
            'parentMenuId'
          )
          commit('SET_MENU_LIST', menuList)
          const asyncRoutes = fnAddDynamicMenuRoutes(
            menuList,
            router.options.routes
          )
          resolve(asyncRoutes)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(state.token) // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(state.token) // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
